﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Flower.SqlServer.Directory.DbGenerator.Generators
{
    internal class SaveProcedures : IGenerator
    {
        public int Order
        {
            get { return 3; }
        }

        public void Generate(TextWriter writer, Settings settings)
        {
            string storedProcedureTemplate, specificInsertionTemplate, specificUpdateTemplate;

            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SaveProcedure.sql")))
            {
                storedProcedureTemplate = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SpecificDataInsertion.sql")))
            {
                specificInsertionTemplate = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SpecificDataUpdate.sql")))
            {
                specificUpdateTemplate = reader.ReadToEnd();
            }

            foreach (EntriesDefinition.EntryDefinition entryDefinition in EntriesDefinition.Entries)
            {
                var builder = new StringBuilder(storedProcedureTemplate);

                if (entryDefinition.SpecificColumns != null)
                {
                    string entrySpecificInsertion = string.Empty;
                    string entrySpecificUpdate = string.Empty;

                    if (entryDefinition.SpecificInsertScriptResource != null)
                    {
                        using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(string.Concat(Program.ScriptsNamespace, ".", entryDefinition.SpecificInsertScriptResource, ".sql"))))
                        {
                            entrySpecificInsertion = reader.ReadToEnd();
                        }
                    }

                    if (entryDefinition.SpecificUpdateScriptResource != null)
                    {
                        using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(string.Concat(Program.ScriptsNamespace, ".", entryDefinition.SpecificUpdateScriptResource, ".sql"))))
                        {
                            entrySpecificUpdate = reader.ReadToEnd();
                        }
                    }

                    if (entryDefinition.SpecificColumns.Values.Any(col => !col.DontGenrateInsertUpdate))
                    {
                        builder
                            .Replace("/*--SpecificDataInsertion--*/", string.Concat(specificInsertionTemplate, "\n\n", entrySpecificInsertion))
                            .Replace("/*--SpecificDataUpdate--*/", string.Concat(specificUpdateTemplate, "\n\n" ,entrySpecificUpdate));
                    }
                    else
                    {
                        builder
                            .Replace("/*--SpecificDataInsertion--*/", entrySpecificInsertion)
                            .Replace("/*--SpecificDataUpdate--*/", entrySpecificUpdate);
                    }

                    var specificColumns = entryDefinition.SpecificColumns.ToList();

                    var additionalArgs = new StringBuilder();
                    var sets = new StringBuilder();
                    var vals = new StringBuilder();
                    var cols = new StringBuilder();

                    for (int i = 0; i < specificColumns.Count; i++)
                    {
                        if (i > 0)
                        {
                            if (!specificColumns[i].Value.DontGenrateInsertUpdate)
                            {
                                sets.AppendLine(",");
                                vals.Append(", ");
                                cols.Append(", ");
                            }
                        }

                        if (!specificColumns[i].Value.DontGenrateInsertUpdate)
                        {
                            sets.AppendFormat("\t\t\t{0} = @{0}", specificColumns[i].Key);
                            cols.AppendFormat("{0}", specificColumns[i].Key);
                            vals.AppendFormat("@{0}", specificColumns[i].Key);
                        }

                        additionalArgs.AppendFormat
                        (
                            "\t@{0} {1}{2},", 
                            specificColumns[i].Key, 
                            specificColumns[i].Value.Type,
                            (specificColumns[i].Value.Readonly) ? " READONLY" : string.Empty
                        );

                        if (i < specificColumns.Count - 1)
                        {
                            additionalArgs.AppendLine();
                        }
                    }

                    builder
                        .Replace("/*--AdditionalArgs--*/", additionalArgs.ToString())
                        .Replace("/*--SpecificDataSets--*/", sets.ToString())
                        .Replace("/*--SpecificDataValues--*/", vals.ToString())
                        .Replace("/*--SpecificDataColumns--*/", cols.ToString());
                }
                else
                {
                    builder
                        .Replace("/*--SpecificDataInsertion--*/", string.Empty)
                        .Replace("/*--SpecificDataUpdate--*/", string.Empty)
                        .Replace("/*--AdditionalArgs--*/", string.Empty);
                }

                builder
                    .Replace("/*--EntryName--*/", entryDefinition.Name)
                    .Replace("/*--DirectoryEntryType--*/", entryDefinition.DirectoryEntryType.ToString());

                writer.WriteLine(builder);
                writer.WriteLine();
            }
        }
    }
}
